package org.jaaksi.test.jpush;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;
import org.jaaksi.test.jpush.model.push.JPushBean;
import org.jaaksi.test.jpush.model.push.JPushFromBean;
import org.jaaksi.test.jpush.model.push.MsgPushFeedBean;
import org.jaaksi.test.jpush.ui.HouseFeedActivity;
import org.jaaksi.test.jpush.util.ConstantUtils;
import org.jaaksi.test.jpush.util.DataUtil;
import org.jaaksi.test.jpush.util.EventBusTool;

import java.util.Random;

/**
 * Created by Fcy on 2016/1/23. JPush广播receiver
 */
public class JPushReceiver extends BroadcastReceiver
{
	public static final int REPLY_NOTIFY_ID = 2;

	@Override
	public void onReceive(Context context, Intent intent)
	{
		if (intent != null && intent.getExtras() != null)
		{
			Bundle bundle = intent.getExtras();
			if (JPushInterface.ACTION_MESSAGE_RECEIVED
			        .equals(intent.getAction()))
			{
				// 这里传递的json，与服务器协定格式，根据type判断推送的类型
				String json = bundle.getString(JPushInterface.EXTRA_MESSAGE);
				Log.e("fcy", "----------------- receiver msg=\n" + json);
				JPushBean pushBean = DataUtil.getBean(json, JPushBean.class);
				if (pushBean != null)
				{
					initData(pushBean);
				}
			}
		}
	}

	private void initData(JPushBean pushBean)
	{
		String content = pushBean.alert;
		Intent intent = null;

		JPushFromBean pushFromBean = pushBean.from;
		switch (pushFromBean.type)
		{
			case ConstantUtils.SourceType.HOUSE: // 房源
				// 更新未读消息个数
				MsgPushFeedBean housePushFeedBean = MyApplication
				        .getInstance().mSpFactory.getHousePushFeedData();
				updateMsgPushFeedBean(housePushFeedBean, pushFromBean.type);
				MyApplication.getInstance().mSpFactory
				        .setHousePushFeedData(housePushFeedBean);
				intent = new Intent(MyApplication.getInstance(),
				        HouseFeedActivity.class);

				// 这里可以根据不同的类型，设置不同的tag，取代发通知
				EventBusTool.post("", ConstantUtils.EventTag.UPDATE_POINT);
				EventBusTool.post("",
				        ConstantUtils.EventTag.UPDATE_SOURCE_HOUSE);
				// EventBusTool.post(housePushFeedBean.feed, "source_house");
				break;
			case ConstantUtils.SourceType.CUSTOMER: // 客源
				MsgPushFeedBean customerPushFeedBean = MyApplication
				        .getInstance().mSpFactory.getCustomerPushFeedData();
				updateMsgPushFeedBean(customerPushFeedBean, pushFromBean.type);
				MyApplication.getInstance().mSpFactory
				        .setHousePushFeedData(customerPushFeedBean);

				EventBusTool.post("", ConstantUtils.EventTag.UPDATE_POINT);
				EventBusTool.post("",
				        ConstantUtils.EventTag.UPDATE_SOURCE_CUSTOMER);
				break;
		}

		if (intent != null)
		{
			showNotification(intent, content, content, "未读消息提醒");
		}
	}

	/**
	 * 更新消息数目
	 * 
	 * @param msgPushFeedBean
	 * @param type
	 */
	private void updateMsgPushFeedBean(MsgPushFeedBean msgPushFeedBean,
	        int type)
	{
		msgPushFeedBean.time = System.currentTimeMillis();
		switch (type)
		{
			case ConstantUtils.BuyType.NEWHOUSE:
				msgPushFeedBean.unReadNewHouse++;
				break;
			case ConstantUtils.BuyType.ERSHOU:
				msgPushFeedBean.unReadErShou++;
				break;
			case ConstantUtils.BuyType.RENT:
				msgPushFeedBean.unRent++;
				break;
		}

	}

	/**
	 * 显示 通知
	 *
	 * @param intent
	 * @param notifyContent
	 *            下拉通知的内容
	 * @param tickerString
	 *            显示在通知栏中的内容
	 * @param contentTitle
	 *            下拉通知的title
	 */
	private void showNotification(Intent intent, String notifyContent,
	        String tickerString, String contentTitle)
	{

		int icon = MyApplication.getInstance().getApplicationInfo().icon;
		// 第二个参数中的id，对于多个消息要用不同的值，
		// 这样才能保证每个消息对应的Intent的值不同，相同id的通知会被覆盖掉
		PendingIntent pend = PendingIntent.getActivity(
		        MyApplication.getInstance(), new Random().nextInt(), intent, 0);
		NotificationCompat.Builder builder = new NotificationCompat.Builder(
		        MyApplication.getInstance());
		builder.setContentIntent(pend).setSmallIcon(icon)
		        .setWhen(System.currentTimeMillis()).setTicker(tickerString)
		        .setContentTitle(contentTitle).setContentText(notifyContent)
		        .setAutoCancel(true);
		NotificationManager man = (NotificationManager) MyApplication
		        .getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = builder.build();
		// notification.sound = RingtoneManager
		// .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // 系统默认铃声

		Uri soundUri = Uri.parse("android.resource://"
		        + MyApplication.getInstance().getPackageName() + "/"
		        + R.raw.notification_alert);
		notification.sound = soundUri;
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		// 通知不可以清除，必须手动调用api清除
		// notification.flags |= Notification.FLAG_NO_CLEAR;
		// 通知可以清除，点击通知后自动消失
		notification.flags = Notification.FLAG_AUTO_CANCEL;

		man.notify(REPLY_NOTIFY_ID, notification);

	}
}
